import {Row, Col, Icon,Spin,Button} from 'antd';
import {routerShape} from 'react-router';
import {WeaDialog, WeaMap} from 'ecCom';
import includes from 'lodash/includes';
import isEqual from 'lodash/isEqual';
import { WeaLocaleProvider,WeaAudio,WeaAvatar } from 'ecCom';
import {getLogAllReceiveUser} from "../../apis/api";
import {getLocationInfoData} from './util';
import ReplyDialog from '../form-logList/ReplyDialog';
import ContentList from '../form-logList/ContentList';
import { toJS } from  'mobx';
const getLabel = WeaLocaleProvider.getLabel;

export default class SignListItem extends React.Component {
    static contextTypes = {
        router: routerShape
    }

    constructor(props) {
        super(props);
        this.state = {
            showrivebtnspan: false,
            allReceiveUser:'',
            showUsers:false,
            loading:false,
            mapDialogState: false,
            checkCommunication: props.store.communicateSettingKey.isExpendCommunicate || '0'
        }
    }

    // shouldComponentUpdate(nextProps, nextState) {
    //     const logid = this.props.data['logid'];
    //     const lindex = (this.props.showuserlogids).indexOf(logid) > -1
    //     const eindex = (nextProps.showuserlogids).indexOf(logid) > -1;
    //     return !isEqual(this.props.data, nextProps.data) ||
    //         this.props.isShowUserheadimg !== nextProps.isShowUserheadimg ||
    //         lindex !== eindex ||
    //         this.state.showrivebtnspan !== nextState.showrivebtnspan
    // }

    componentWillReceiveProps(nextProps){
        if(this.props.data['logid'] != nextProps.data['logid']) {
            this.setState({
                showrivebtnspan: false,
                allReceiveUser:'',
                showUsers:false,
                loading:false,
                checkCommunication: nextProps.store.communicateSettingKey.isExpendCommunicate
            });
        }
    }
    //地图上查看当前链接位置
    showMapDialog = (bool) => {
      this.setState({mapDialogState: bool})
    }
  

    render() {

        const {data = {}, isShowUserheadimg, forward, forwardEvent, requestid, workflowid, showuserlogids = [], authSignatureStr, authStr, isOpenCommunication} = this.props;
        const { communicateSettingKey: { isShowSignCommunicate }, hasSubmitRight = false } = this.props.store;
        const {
            logid, displaydepid = '', img_path = '', isexsAgent, log_agentorbyagentid = '', displaybyagentname = '', displayid,displaytype, displayname = '',
            displaydepname, log_remarkHtml = '', annexdocs = [], signdocs = [], signwfs = [], userimg = '',signnaturImgHeight,
            remarkLocation ='',speechAttachmetnDatas = [], commentList = []
        } = data;
        const {receiveUser = '', receiveUserCount = 0, log_operatedate, log_operatetime, log_nodename, operationname, isReference} = data;
        const {showrivebtnspan,allReceiveUser = '',showUsers = false,loading = false,checkCommunication = false} = this.state;

        const dpurl = "/hrm/company/HrmDepartmentDsp.jsp?id=" + displaydepid;
        let locationInfoData = getLocationInfoData(remarkLocation);
       
        return (
            <div className='wf-req-sign-list-content'>
                <div className='content-left' style={{'paddingLeft': isShowUserheadimg ? '48px' : '0px'}}>
                    {isShowUserheadimg && displaytype == '0' &&
                    // <img src={img_path} className='content-text-left-user-img'/>
                    <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@11yq81`} userId={displayid}/>
                    }
                    {isShowUserheadimg && displaytype == '1' &&
                    <img src={img_path} className='content-text-left-user-img'/>
                    }
                    <div style={{'width': '132px'}}>
                        <p>
                            {isexsAgent && <a href={`javaScript:openhrm(${log_agentorbyagentid})`}
                                              onClick={event => window.pointerXY(event)}>{displaybyagentname}</a>}
                            {isexsAgent && <span style={{color: "#2db7f5"}}>{`->`}</span>}
                            { displaytype==0 ? <a href={`javaScript:openhrm(${displayid})`}
                                onClick={event => window.pointerXY(event)}>{displayname}</a> :
                                <a target={`_blank`}  href={`/spa/crm/static/index.html#/main/crm/customerView?customerId=${displayid}`} >{displayname}</a>}
                        </p>
                        <span style={{wordBreak:'break-word'}}>
							<a href={dpurl} target="_blank" style={{color: '#9b9b9b', 'white-space': 'pre-wrap'}}>
								{displaydepname}
							</a>
						</span>
                    </div>
                </div>
                <div className='content-right'
                    onMouseEnter={() => {this.setState({showrivebtnspan: true})}}
                    onMouseLeave={() => {this.setState({showrivebtnspan: false})}}>
                    <div className='content-right-remark-html' dangerouslySetInnerHTML={{__html: log_remarkHtml}}/>
                    {
                        speechAttachmetnDatas &&
                        speechAttachmetnDatas.map((r,audioIndex) => {
                            return (
                                <WeaAudio ecId={`${this && this.props && this.props.ecId || ''}_WeaAudio@t9v2to@${audioIndex}`} id={`audio_${logid}_${audioIndex}`} onRef={(e) => {}} src = {r} />
                            )
                        })
                    }
                    {annexdocs.length > 0 && <div className='content-right-docs'>
                        <i className='icon-mail-enclosure'/>
                        <div>
                            {annexdocs.map((d = {}) => {
                                const {filelink = '', tempshowname = '', fileExtendName = '', downloadlink = '', docImagefileSize, showdownload} = d;
                                return <p><a target='_blank'
                                             href={filelink}>{`${tempshowname}.${fileExtendName}`}</a>{' '}{showdownload == true && <a
                                    onClick={() => {
                                        this.download(`${downloadlink}&_t=${new Date().getTime()}`);
                                    }}>{`[下载(${(docImagefileSize / 1000).toFixed(1)}k)]`}</a>}</p>
                            })}
                        </div>
                    </div>
                    }
                    {signdocs.length > 0 && <div className='content-right-docs'>
                        <i className='icon-search-File'/>
                        <div>
                            {signdocs.map((d = {}) => {
                                return <p><a target='_blank' href={d['filelink']}>{d['tempshowname']}</a></p>
                            })}
                        </div>
                    </div>
                    }
                    {signwfs.length > 0 && <div className='content-right-docs'>
                        <i className='icon-coms-workflow'/>
                        <div>
                            {signwfs.map((w = {}) => {
                                return <p><a target='_blank' onClick={() => {
                                    openFullWindowHaveBar(`/workflow/request/ViewRequestForwardSPA.jsp?requestid=${w['requestid']}&isrequest=1&isovertime=0&desrequestid=${w['desrequestid']}&authStr=${authStr}&authSignatureStr=${authSignatureStr}`)
                                }}>{w['title']}</a></p>
                            })}
                        </div>
                    </div>
                    }
                    {
                      (remarkLocation !== 'null')  && (locationInfoData.longitude) && <div className='content-right-docs'>
                          <i className="icon-coms-position" title={getLabel(22981, "位置")} />
                          <div>
                          <a onClick={() => {window.openlocation(remarkLocation)}}>{locationInfoData.name}</a>
                          </div>

                      </div>
                    }
                    {userimg &&
                    <div className="content-right-userimg">
                        <img  style={{'maxHeight':`${signnaturImgHeight}px`}}  id="markImg" src={userimg}></img>
                    </div>
                    }

                    {!showUsers &&
                        <p className={'logitem-Recipient'}>
                            <span>{getLabel('15525',"接收人")} : </span>
                            {receiveUser.replace(/,/g, ' ')}
                            {loading && <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@9t2uly`} size={"small"}/>}
                            {!loading && receiveUserCount > 20 && <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@1ohhhw`} className='content-text-right-open-btn' type='down'
                                                               onClick={() => this.controllShowAllLogOperator(logid)}/>
                            }
                        </p>
                    }
                    {showUsers &&
                        <div className='wf-req-sign-list-users'>
                            <div style={{color: '#323232', paddingRight: 20}}>
                                <span style={{color: '#c0c0c0'}}>{getLabel('15525',"接收人")} : </span>
                                {allReceiveUser.replace(/,/g, ' ')}
                            </div>
                            {<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@xibs21`} className='content-text-right-open-btn' type='up'
                                  onClick={() => this.controllShowAllLogOperator(logid)}/>}
                        </div>
                    }
                    <p style={{lineHeight: '22px', marginTop: 10, color: '#9a9a9a'}}>
                        <span style={{marginRight: 8}}>{`${log_operatedate} ${log_operatetime} `}</span>
                        <span>{`[${log_nodename} / ${operationname}]`}</span>
                        {
                          showrivebtnspan  && <span className="funcbtn reqlogbtn">
                            <span style={{cursor: 'pointer'}}>
                            {
                                isOpenCommunication !== 0  && hasSubmitRight && <span onClick={this.replyClick.bind(this, data)}
                                style={{ marginRight: 16 }}>
                                    <i className='icon-coms-message-o' style={{ marginRight: 6 }} />
                                    {getLabel(385534, "回复")}
                                </span>  
                              }
                              {
                                forward == '1' && <span onClick={() => typeof forwardEvent === 'function' && forwardEvent(displayid)}
                                style={{ marginRight: 16 }}>
                                  <i className='icon-xxx-form-Forward' style={{marginRight: 6}}/>{getLabel('6011',"转发")}
                                </span>
                              }
                              
                            </span>
                          </span>

                        }
                    </p>

                </div>
                
                     {/* 回复逻辑代码 */}
                     {
                     isShowSignCommunicate == '1' && Array.isArray(toJS(commentList)) && toJS(commentList).length > 0 && <div className='communication-area-wrap'>
                      {
                        (checkCommunication == '0')? <div className='communication-folder-panel' onClick={() => {this.clickCheckCommunication()}}>
                              <span className='word-span' title={getLabel(519614,'展开交流')}>{getLabel( '519614', '展开交流')}</span>
                            <i className="icon-coms-down-001" />
                          </div>
                        : [
                          <div className={checkCommunication? 'communication-folder-panel open': 'communication-folder-panel'} onClick={() => {this.clickCheckCommunication()}}>
                            <span className='word-span' title={getLabel(519615, '收起交流')}>{getLabel('519615', '收起交流')} </span>
                            <i className="icon-coms-up-001" />
                           </div>,
                          <ContentList 
                            ecId={`${this && this.props && this.props.ecId || ''}_ContentList@9s4bmo@${logid}`} 
                            isFromPortal={true} 
                            logid={logid} 
                            commentList={toJS(commentList)} 
                            logListStore={this.props.store}
                          />
                        ]
                      }
                    </div>
                  }
            </div>
        )
    }

    replyClick = (data) => {
      let isOpenSignCommunicate = true;
      let str = data.log_remarkHtml;
      let remarkStr =  '<div class="wrap_box">'+ str +'</div>';
      let remarkElement = $(remarkStr);
      remarkElement.children().filter(".container_form_wrap") && remarkElement.children().filter(".container_form_wrap").remove();
      remarkElement.children().filter("span:not(#wea_rich_text_default_font)") && remarkElement.children().filter('span:not(#wea_rich_text_default_font)').remove();
      let newStr = remarkElement.html(); //还原成字符串
      str = this.imgUtil(newStr);
      this.getReplyDialog(data, str);
    }
    getReplyDialog = (data, replyRemarkStr) => {
      const { store } = this.props;
      let replyDialog = document.getElementById('reply-dialog-warp');
      if(!replyDialog) {
        replyDialog = document.createElement('div');
        replyDialog.setAttribute('id', 'reply-dialog-warp');
        document.body.appendChild(replyDialog);
      } 
      let com = (
        <ReplyDialog ecId={`${this && this.props && this.props.ecId || ''}_ReplyDialog@m9aep0`} replyInfo={data} replyRemarkStr={replyRemarkStr} store={store}/>
      );
      ReactDOM.render(com, replyDialog);
    }
    clickCheckCommunication = () => {
      const {checkCommunication } = this.state;
      if(checkCommunication == '0') {
        this.setState({checkCommunication: '1'});
      } else {
        this.setState({checkCommunication: '0'});
      }
    }
    controllShowAllLogOperator(logid){
        let {showUsers = false,allReceiveUser = '',loading = false} = this.state;
        if(!showUsers && allReceiveUser == '' && !loading) {
            this.setState({loading:true});
            getLogAllReceiveUser({logid}).then(data=>{
                this.setState({loading:false,showUsers:true,allReceiveUser:data.receivedPersons});
            })
        } else {
            this.setState({showUsers:!showUsers});
        }
    }

    imgUtil(srcHtml__) {
        if (srcHtml__.indexOf("small_pic") > -1 || srcHtml__.indexOf("SMALL_PIC") > -1) {
            var firstnum = srcHtml__.indexOf("<div");
            if (firstnum == -1) {
                firstnum = srcHtml__.indexOf("<DIV");
            }
            var begin_srcHtml = srcHtml__.substring(0, firstnum);
            var cycle_begin = "";
            var new_srcHtml = "";
            var end_srcHtml = "";
            var divwords = "";

            //alert(srcHtml__);
            var cycleString = srcHtml__.substring(firstnum);
            while (cycleString.indexOf("<img") > -1 || cycleString.indexOf("<IMG") > -1) {
                //得到div图片之间的文字
                var j = cycleString.indexOf("</div");
                if (j == -1) {
                    j = cycleString.indexOf("</DIV");
                }
                var divwordstemp = cycleString.substring(j + 6);
                var k = divwordstemp.indexOf("<div");
                if (k == -1) {
                    k = divwordstemp.indexOf("<DIV");
                }
                divwords = divwordstemp.substring(0, k);
                begin_srcHtml += divwords;
                //第一个img
                var b = cycleString.indexOf("<img");
                if (b == -1) {
                    b = cycleString.indexOf("<IMG");
                }
                cycleString = cycleString.substring(b);
                var e = cycleString.indexOf(">");
                cycleString = cycleString.substring(e + 1);
                //第二个img
                var m = cycleString.indexOf("<img");
                if (m == -1) {
                    m = cycleString.indexOf("<IMG");
                }
                cycleString = cycleString.substring(m);
                var imgString = "";
                var n = cycleString.indexOf(">");
                imgString = cycleString.substring(0, n);
                cycleString = cycleString.substring(n + 1);
                imgString = imgString.replace("class=\"maxImg\"", "");
                begin_srcHtml += "<p> " + imgString + "/> </p>";
                end_srcHtml = cycleString;
            }
            var r = end_srcHtml.indexOf("</div>");
            if (r == -1) {
                r = end_srcHtml.indexOf("</DIV>");
            }
            end_srcHtml = end_srcHtml.substring(r + 6);
            begin_srcHtml += end_srcHtml;
            srcHtml__ = begin_srcHtml;
        }
        return srcHtml__;
    }

    download(url) {
        jQuery('#WfFormFileDownload').attr('src', url);
    }
}